package org.apache.solr.client.example;

import java.net.URL;
import java.util.Map;

import org.apache.solr.client.QueryResults;
import org.apache.solr.client.ResultDoc;
import org.apache.solr.client.SolrClient;
import org.apache.solr.client.SolrQuery;
import org.apache.solr.client.impl.SolrClientImpl;
import org.apache.solr.client.util.SimpleSolrDoc;

public class SimpleExample 
{
	// This sets up an example client pointed to the default server
	// follow the tutorial in:
	//  http://incubator.apache.org/solr/tutorial.html
	// This assumes a server is running:
	//  java -jar start.jar
	public static void main( String[] args )
	{
		try {
			SolrClient client = new SolrClientImpl( new URL("http://localhost:8983/solr/") );
			
			// Set up a simple query
			SolrQuery query = new SolrQuery();
			query.addFacetField( "cat" );
			query.setFacetLimit( 15 );
			query.setQuery( "video" );
			query.setShowDebugInfo( true );
			
			//by default, sort by score...
			query.addSortField( "price", SolrQuery.ORDER.desc );
			query.setIncludeScore( true );
			
			System.out.println( "sending: "+query );
			QueryResults results = client.query( query );
			System.out.println( "got: "+results.getNumFound() + " :: "+results.getQTime() );
			
			for( ResultDoc doc : results.getDocs() ) {
				System.out.println( "["+doc.getId()+"] "+ doc.getField( "name" ) );
				
				// Show each field
				for( Map.Entry<String, Object> f : doc.getField().entrySet()) {
					System.out.println( " \""+f.getKey()+"\" = " + f.getValue() );
	        	}
				
				System.out.println( "score: "+doc.getScore()+ " -- "+doc.getExplain() );
				System.out.println();
			}
			
			// Adding a document
			String id = "test-1000000";
			SimpleSolrDoc ex = new SimpleSolrDoc();
			ex.setField( "id", id );
			ex.setField( "name", "SimpleExample Test Doc" );
			ex.setField( "price", 12.34f );
			ex.setField( "cat", new String[] { "aaa", "bbb", "ccc" } );
			client.add( ex );
			
			client.commit( true, true );
			
			query = new SolrQuery();
			query.setQuery( "id:"+id );
			results = client.query( query );
			if( results.getNumFound() != 1 ) {
				throw new Exception( "should have found 1" );
			}
			System.out.println( "found: "+results.getFirstResult().getField( "name" ) );

			client.optimize( true, true );
		}
		catch( Exception ex ) {
			ex.printStackTrace();
		}
	}
}
